class Resource:
    """ORM 数据库资源增删改查"""
    def __init__(self, model):
        self.model = model

    def get_item_by_filter(self, db, filter_):
        """筛选单条"""
        return db.query(self.model).filter(**filter_).first()

    def get_items_by_filter(self, db, filter_, page: int = None, page_size: int = None, order_by: str = None):
        """筛选多条"""
        q = db.query(self.model).filter(**filter_)
        if page and page_size:
            q = q.offset((page - 1) * page_size).limit(page_size)
        if order_by:
            q = q.order_by(order_by)
        return {'count': q.count(), 'data': q.all()}

    def create_item(self, db, item_):
        """创建单条"""
        item = self.model(**item_)
        db.add(item)
        db.commit()
        return item

    def create_items(self, db, items_):
        """创建多条"""
        items = [self.model(**item_) for item_ in items_]
        db.add_all(items)
        db.commit()
        return len(items)

    def update_item_by_filter(self, db, filter_, update):
        """修改单条"""
        item = db.query(self.model).filter(**filter_).first()
        if not item:
            raise Exception('资源未找到')

        for k, v in update.items():
            if getattr(item, k) == v:
                continue
            setattr(item, k, v)
        db.commit()
        return item

    def update_items_by_filter(self, db, filter_, update):
        """批量修改"""
        items = db.query(self.model).filter(**filter_).all()
        if not items:
            return 0

        for item in items:
            for k, v in update.items():
                if getattr(item, k) == v:
                    continue
                setattr(item, k, v)
        db.commit()
        return items.count()

    def delete_item_by_filter(self, db, filter_):
        """删除单条"""
        item = db.query(self.model).filter(**filter_).first()
        if not item:
            raise Exception('服务未找到')
        db.delete(item)
        db.commit()
        return

    def delete_items_by_filter(self, db, filter_):
        """批量删除"""
        count = db.query(self.model).filter(**filter_).delete()
        return count


class Route:

    def get(self):
        pass

    def post(self):
        pass

    def put(self):
        pass

    def delete(self):
        pass


class ExampleRoute(Route):
    schema = 'userSchema'
    model = 'user'
    auth = ''
    permit = ''
